// ajax模块
// 依赖 layer,jquery

/**
 * 显示loading框
 */
const showLoading = () => {
    if (!window['layer']) {
        return
    }
    const i = layer.load(0, {
        shade: [0.3, '#000']
    })
    return i
}

/**
 * 隐藏loading框
 * @param {number} i loading框的索引号，可不传，隐藏所有loading框
 */
const hideLoading = i => {
    if (!window['layer']) {
        return
    }
    if (i) {
        layer.close(i)
    } else {
        layer.closeAll('loading')
    }
}

/**
 * 发起ajax请求，支持同时发起多个请求，单个请求resolve(res)，多个请求resolve([res])
 * @param {*} p jquery ajax options
 */
const ajax = p => {
    return new Promise((resolve, reject) => {
        if (!$ || !$.ajax) {
            reject('ajax请求依赖jquery，请引入')
            return
        }
        (async function () {
            try {
                let i = showLoading()
                let [...ress] = await Promise.all(p.map(x => {
                    return new Promise((resolve, reject) => {
                        $.ajax(Object.assign(
                            {
                                type: 'GET',
                                contentType: 'application/json',
                                dataType: 'json',
                                crossDomain: true,
                                xhrFields: {
                                    withCredentials: true
                                }
                            }, x, {
                                success(res) {
                                    resolve(res)
                                },
                                error(err) {
                                    reject(err)
                                }
                            }
                        ))
                    })
                }))
                hideLoading(i)
                if (ress.length === 1) {
                    resolve(ress[0])
                } else {
                    resolve(ress)
                }
            } catch (e) {
                reject(e)
            }
        }())
    })
}

export {
    ajax
}